<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage show-footer>
      <div>
        <form>
          <div style="display: flex;margin-top: -30px;margin-left: 10px;align-items: center;">
            <n-form-item>
              <label>仓库名称：</label>
              <n-input
                v-model:value="searchCondition.name"
                placeholder="请输入仓库名称"
                style="width: 180px"></n-input>
            </n-form-item>
            <n-form-item style="margin-left: 10px">
              <label >仓库类型：</label>
              <n-select v-model:value="searchCondition.type" :options="options"/>
            </n-form-item>
            <n-form-item>
              <n-button style="--n-width: 70px; margin-left: 10px;" type="primary"  @click="searchByCondition()">
                筛选
              </n-button>
            </n-form-item>
            <n-form-item style="margin-left: 10px">
                <n-button type="primary" @click="showForm = true" >添加仓库</n-button>
            </n-form-item>
            <n-form-item>
              <n-button style="--n-width: 70px; margin-left: 10px;padding: 0" type="error"  @click="deleteSelectStores()">
                批量删除
              </n-button>
              <n-form-item style="margin-left: 10px">
                <n-button type="primary"
                          @click="exportListInfo"
                >导出</n-button>

              </n-form-item>
            </n-form-item>
          </div>
        </form>
        <StoreAdd :show="showForm" @update-page="searchByCondition" :onClose="handleClose"/>
        <UpdateStore
            @update-page="searchByCondition"
            :show1="showForm1"
            :onClose="handleClose"
            :store="currentStore"
        />
        <n-data-table
            remote
            :single-line="false"
            ref="table"
            :columns="columns"
            :data="storeList"
            :loading="loading"
            :pagination="paginationReactive"
            :row-key="rowKey"
            :scroll-x="900"
            @update:checked-row-keys="handleCheck"
        />
      </div>
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import {h, onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import StoreAdd from './components/store-add.vue';
import CategoryActions from "@/views/admin/category/components/category-actions.vue";
import UpdateStore from './components/store-edit.vue'

const currentStore = ref(null);
const stores=ref([])
  stores.value.push({
    label:'全部',
    value:-1,
})
const exportListInfo = async () => {
  const res = await api.exportStoreList({
    name:searchCondition.value.name,
    type:searchCondition.value.type,

  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if(contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
  if(window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else{
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.download= fileName;
    elink.style.display ="none"
    elink.href  = window.URL.createObjectURL(blob)
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const queryStoreList = async () => {
  loading.value = true
  try {
    const res = await api.findAllStore()
    if(res.code === 200) {
      res.data.map((item)=>{
        stores.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库信息失败！")
  }finally{
    loading.value = false
  }
}

const showForm = ref(false);
const showForm1=ref(false);
const searchCondition = ref({
 name:'',
  type: "",
});
const handleClose = () => {
  showForm.value = false;
  showForm1.value=false;
};
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const logList = ref([])
const range = ref(null)
const options = ref([
  {
    label: '全部',
    value: '全部',
  },
  {
    label: '本地仓',
    value: '本地仓'
  },
  {
    label: '海外仓',
    value: '海外仓'
  },
	{
		label: '平台仓',
		value: '平台仓'
	},
]);
const checkedRowKeysRef = ref([]);
const handleCheck =(rowKeys)=>{
  checkedRowKeysRef.value = rowKeys;
}
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 30,
  },
  {
    key: 'name',
    title: '仓库名称',
    width: 90,

  },
  {
    key: 'address',
    title: '仓库地址',
    width: 100,
  },
  {
    key: 'type',
    title: '仓库类型',
    width: 70,
  },
  {
    key: 'storeManagerName',
    title: '负责人',
    width:70,
  },
  {
    key: 'adminName',
    title: '创建人',
    width:70,
  },
  {
    key: 'createTime',
    title: '创建时间',
    width: 100,
    align:'left',
  },
  {
    key: 'operation',
    title: '操作',
    width: 100,
    render(row) {
      return h(
        CategoryActions,
        {
          onClickDelete: () => onDeleteStore(row),
          onClickEdit: () => onDetailStore(row),
        }
      );
    }
  },
]
let total = 0
const paginationReactive = reactive({
  page: 1,
  pageSize: 50,
  showSizePicker: true,
  pageSizes: [50, 100, 150],
  itemCount:0,
  prefix: () => {
    return '查询出 ' + total + '条记录';
  },
  onChange: (page) => {
    paginationReactive.page = page;
    queryByPage()
  },
  onUpdatePageSize: (pageSize) => {
    paginationReactive.pageSize = pageSize;
    paginationReactive.page = 1;
    queryByPage()
  }
});
const deleteSelectStores = ()=>{
  if(checkedRowKeysRef.value.length <= 0) {
    $message.error("当前并未选择仓库！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选仓库？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      console.log(ids)
      loading.value = true
      try {
        const res = await api.deleteStores({ params: { ids } })
        if(res.code === 200) {
          $message.success("删除所选仓库成功！")
          // await queryByPage()
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选仓库失败！")
      }finally{
        loading.value = false
      }
    },
  })
}
const searchByCondition = async ()=>{
  loading.value = true
  try {
    paginationReactive.page = 1;
    const res = await api.findPageStore({
      params: {
        name:searchCondition.value.name,
        type:searchCondition.value.type,
        pageNum: paginationReactive.page,
        pageSize: paginationReactive.pageSize,
      }
    })
    if(res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
      storeList.value = res.data.records.map((item,i)=>{
        return {...item,
          colId: baseCount + i + 1,
        }
      })
      $message.success("获取仓库成功！")
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("查询仓库失败！")
  }finally{
    loading.value = false
  }
}
const onDeleteStore = async (store)=>{
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前仓库？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const {id} = store
      loading.value = true
      try {
        const res = await api.deleteStore({id})
        if(res.code === 200) {
          $message.success("删除仓库成功！")
          // await queryByPage()
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除仓库失败！")
      }finally{
        loading.value = false
      }
    }
  })
}
const onDetailStore = async (store)=>{
  currentStore.value = store;
  showForm1.value = true;
  await router.push({name: 'AdminLogDetail', params: {storeId: id}});
}
const storeList=ref([])
const queryByPage = async () => {
  loading.value = true
  try {
    const res = await api.findPageStore(
      {
        params: {
          pageNum: paginationReactive.page,
          pageSize: paginationReactive.pageSize,
        }
      })
    if (res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      storeList.value = res.data.records.map((item, i) => {
        return {
          ...item,
          colId: i + 1
        }
      })
      $message.success("获取仓库成功！")
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库失败！")
  }finally{
    loading.value = false
  }
}
const rowKey = (rowData) => {
  return rowData.id
}
onMounted(()=>{
  queryByPage()
  queryStoreList()

})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
  text-align: center;

}
:deep(.n-select) {
  width: 140px !important;
}

:deep(.two-line-description) {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 控制显示的行数 */
  overflow: hidden;
}

</style>
